package com.freecloud.javabasics.design.observer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册监听事件与观察者
 * 并通知观察者
 * @Author: maomao
 * @Date: 2019-11-19 09:29
 */
public class EventLisenter {

    private Map<Enum,Event> eventMap = new HashMap<>();

    public void addLisenter(Enum eventType, Object target, Method callback){
        eventMap.put(eventType,new Event(target,callback));
    }

    protected void trigger(Enum eventType){
        if(!eventMap.containsKey(eventType)){
            return;
        }
        Event e = eventMap.get(eventType);
        e.setTrigger(eventType.toString());

        trigger(e);
    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try {
            //调用对应观察者实例方法
            event.getCallback().invoke(event.getTarget(),event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
